<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Config;
use think\Db;
use think\Request;

class CollectData extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("hotel_id")) {
            $map['hotel_id'] = ["like", "%" . $this->request->param("hotel_id") . "%"];
        }
        if ($this->request->param("remark")) {
            $map['remark'] = ["like", "%" . $this->request->param("remark") . "%"];
        }
    }

    /**
     * 首页
     */
    public function index()
    {
        $data = input();
        // 查询条件
        if ($data['room_type_id']){
            $room_type_id = Db::name('room_hotel_number')->where('room_type_id',$data['room_type_id'])->field('hotel_id')->select();
            if ($room_type_id){
                $roomTypeId = '';
                foreach ($room_type_id as $index => $item) {
                    $roomTypeId .= $item['hotel_id'].',';
                }
                $roomTypeId = rtrim($roomTypeId,',');
                $map['hotel_id'] = ['in', $roomTypeId];
            }
        }
        if ($data['hotel_id']){
            // 从酒店获取酒店id
            $hotelIds = Db::name('hotel')->where('hotel_name','like',"%{$data['hotel_id']}%")->field('id')->select();
            if ($hotelIds){
                $hotel_id = '';
                foreach ($hotelIds as $index => $hotelId) {
                    $hotel_id .= $hotelId['id'].',';
                }
                $hotel_id = rtrim($hotel_id,',');
                $map['hotel_id'] = ['in',$hotel_id];
            }else{
                $map['hotel_id'] = $data['hotel_id'];
            }
        }
        if ($data['hotel_location']){
            $map['hotel_location'] = ['like',"%{$data['hotel_location']}%"];
        }
        if ($data['start_time']){
            $map['start_time'] = $data['start_time'];
        }
        if ($data['end_time']){
            $map['end_time'] = $data['end_time'];
        }
        if ($data['remark']){
            $map['notes'] = ['like',"%{$data['remark']}%"];
        }
        if ($data['create_time']){
            $start_time = "{$data['create_time']} 0:0:0";
            $end_time = "{$data['create_time']} 23:59:59";
            $map['create_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        switch ($data['settlement_status']){
            case 1: $map['settlement_status'] = 1; break;
            case 2: $map['settlement_status'] = 2; break;
            case 3: $map['settlement_status'] = 3; break;
            default: unset($data['settlement_status']);
        }
        // 查询所有
        if ($this::$isdelete){
            $map['isdelete'] = 1;
        }else{
            $map['isdelete'] = 0;
        }

        $listRows = $this->request->param('numPerPage') ?20: Config::get("paginate.list_rows");
        $list = Db::name('hotel_time_price')->where($map)->order('id','desc')
                                                  ->paginate($listRows, false, ['query' => $this->request->get()]);
//        echo '<br><br><br><br>';
//        dump($list->toArray());
        $hotel_room_type = Db::name('hotel_room_type')->where('isdelete',0)->select();
        $editData = $list->toArray()['data'];
        if ($editData){
            foreach ($editData as $index => $editDatum) {
//                dump(self::getPriceList($editDatum));
                $plicingString = '';
                $plicingData = self::getPriceList($editDatum);
//                dump($plicingData);
                $editData[$index]['collect_data'] = $plicingData;
//                if (is_string($plicingData)){
//                    $editData[$index]['prices_list'] = $plicingData;
//                }else{
//                    foreach ($plicingData as $index2 => $plicingDatum) {
//                        $plicingString .= $plicingDatum.',';
//                    }
//                    $editData[$index]['prices_list'] = rtrim($plicingString,',');
//                }
            }
        }
        $count = $list->count();
        $this->view->assign('searchCondition', $data);
        $this->view->assign('hotel_room_type', $hotel_room_type);
        $this->view->assign('list',$list);
        $this->view->assign('infos',$editData);
        $this->view->assign('page',$list->render());
        $this->view->assign('count',$count);
        return $this->view->fetch();
    }

    /**
     * 编辑页面
     */
    public function edit(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            if (empty($postData['hotel_location'])){
                $postData['hotel_location'] = Db::name('hotel')->where('id',$postData['hotel_id'])->value('hotel_location');
            }
            $updateCount = Db::name('hotel_time_price')->strict(false)->update($postData);
            if ($updateCount){
                return ajax_return_adv('更新成功');
            }else{
                return ajax_return_adv_error('更新失败');
            }
        }else{
            $data = input();
            if (!$data['id']) {
                return ajax_return_adv_error('缺少参数');
            }
            // 查找该结算价格信息
            $vo = Db::name('hotel_time_price')->where('id',$data['id'])->find();
            if ($vo) {
                $vo['hotel_id'] = Db::name('hotel')->where('id',$vo['hotel_id'])->value('hotel_name');
            }
            $this->view->assign('vo',$vo);
            return $this->view->fetch();
        }
    }

    /**
     * 数据汇总列表
     */
    public function priceList()
    {
        $data = input();
        // 从获取结算价格信息
        $info = Db::name('hotel_time_price')->where('id',$data['id'])->find();
        if (!$info){
            return ajax_return_adv_error('不存在该结算价格信息');
        }
        // 查询房价
        $roomRate = Db::name('hotel_room_price')->where('hotel_time_price_id',$data['id'])->select();
        // 根据结算价格的入住日期、结束日期，从房间记录查询酒店那段时间的所有记录
        $tian = round((strtotime($info['end_time'])-strtotime($info['start_time']))/3600/24);
        // 把入住日期与退房日期的相差天数
        $date = [$info['start_time']];
        for ($i=1; $i<= $tian; $i++){
            array_push($date,date("Y-m-d",strtotime("+{$i} day",strtotime("{$info['start_time']}"))));//添加的
        }
        $hotelRecord = Db::name('room_consumption')->where('date_of_stay','in',$date)
            ->where('hotel_id',$info['hotel_id'])->select();
        // 获取该酒店的房型
        $hotelInfo = Db::name('room_hotel_number')->where('hotel_id',$info['hotel_id'])->select();
        if ($hotelInfo){
            foreach ($hotelInfo as $index => $item) {
                $num = 0;
                if ($hotelRecord){
                    foreach ($hotelRecord as $index01 => $item01) {
                        if ($item['hotel_id'] == $item01['hotel_id'] && $item['room_type_id'] == $item01['hotel_room_type_id'] && !empty($item01['num'])){
                            $num += $item01['num'];
                        }
                    }
                    $hotelInfo[$index]['num'] = $num;
                }
                $hotelInfo[$index]['settlement_id'] = $data['id'];
                $hotelInfo[$index]['room_name'] = Db::name('hotel_room_type')->where('id',$item['room_type_id'])->value('room_name');
                if ($roomRate){
                    foreach ($roomRate as $index02 => $item02) {
                        if ($item['hotel_id'] == $item02['hotel_id'] && $item['room_type_id'] == $item02['room_type_id']){
                            $hotelInfo[$index]['price'] = $item02['room_price'];
                        }
                    }
                }
            }
        }
        $count = count($hotelInfo);
        $this->view->assign('vo',$hotelInfo);
        $this->view->assign('count',$count);
        return $this->view->fetch('price_list');
    }


    /**
     * 导出数据
     */
    public function export_to_excel(Request $request)
    {
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l+65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j].$letter[$k];
            }
        }
        $tableHeader = ['ID','酒店名称','酒店位置','开始时间','结束时间','备注','添加时间','是否删除','数据汇总备注','结算状态','房型-使用量-房价-总价'];
        // 查询所有的房型
        $li_length = count($letter);//设置单元格的宽度
        for ($li=0;$li<$li_length;$li++){
            switch ($letter[$li]){
                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);break;
                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);break;
                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(250);break;
                case 'AK':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++){
            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
        }
        if ($data['id']){
            $map['id'] = ['in',$data['id']];
        }
        // 查询条件
        if ($data['hotel_id']){
            // 从酒店获取酒店id
            $hotelIds = Db::name('hotel')->where('hotel_name','like',"%{$data['hotel_id']}%")->field('id')->select();
            if ($hotelIds){
                $hotel_id = '';
                foreach ($hotelIds as $index => $hotelId) {
                    $hotel_id .= $hotelId['id'].',';
                }
                $hotel_id = rtrim($hotel_id,',');
                $map['hotel_id'] = ['in',$hotel_id];
            }else{
                $map['hotel_id'] = $data['hotel_id'];
            }
        }
        if ($data['hotel_location']){
            $map['hotel_location'] = ['like',"%{$data['hotel_location']}%"];
        }
        if ($data['start_time']){
            $map['start_time'] = $data['start_time'];
        }
        if ($data['end_time']){
            $map['end_time'] = $data['end_time'];
        }
        if ($data['remark']){
            $map['notes'] = ['like',"%{$data['remark']}%"];
        }
        if ($data['create_time']){
            $start_time = "{$data['create_time']} 0:0:0";
            $end_time = "{$data['create_time']} 23:59:59";
            $map['create_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        switch ($data['settlement_status']){
            case 1: $map['settlement_status'] = 1; break;
            case 2: $map['settlement_status'] = 2; break;
            case 3: $map['settlement_status'] = 3; break;
            default: unset($data['settlement_status']);
        }
        // 查询所有
        $map['isdelete'] = 0;
        $list = Db::name('hotel_time_price')->where($map)->order('id','desc')->select();
//        dump($list);
        if ($list){
            foreach ($list as $index => $item) {
                $list[$index]['hotel_id'] = Db::name('hotel')->where('id',$item['hotel_id'])->value('hotel_name');
                $list[$index]['hotel_location'] = Db::name('hotel')->where('id',$item['hotel_id'])->value('hotel_location');
                $list[$index]['create_time'] = empty($item['create_time']) ? '':date('Y-m-d H:i:s',$item['create_time']);
                $list[$index]['isdelete'] = empty($item['isdelete']) ? '没删除':'已删除';
                // 组装结算价格的房型房价  房型-使用量-总价
                $price = Db::name('hotel_room_price')->where('hotel_time_price_id',$item['id'])->select();
                // 根据结算价格的入住日期、结束日期，从房间记录查询酒店那段时间的所有记录
                $tian = round((strtotime($item['end_time'])-strtotime($item['start_time']))/3600/24);;
                // 把入住日期与退房日期的相差天数
                $date = [$item['start_time'],$item['end_time']];
                for ($i=1; $i< $tian; $i++){
                    array_push($date,date("Y-m-d",strtotime("+{$i} day",strtotime("{$item['start_time']}"))));//添加的
                }
                if ($date){
                   $jilu =  Db::name('room_consumption')->where('date_of_stay','in',$date)->where('hotel_id',$item['hotel_id'])->select();
                }
                $content = '';
                foreach ($price as $i => $item08) {
                    $num = 0;
                    if ($jilu){
//                        $num = 0;
                        foreach ($jilu as $index09 => $item09) {
                            if ($item09['hotel_id'] == $item08['hotel_id'] && $item09['hotel_room_type_id'] == $item08['room_type_id'] && !empty($item09['num'])){
                                $num += $item09['num'];
                            }
                        }
                        $price[$i]['num'] = $num;
                    }
                    $room_type = Db::name('hotel_room_type')->where('id',$item08['room_type_id'])->value('room_name');
                    $total_price = $item08['room_price'] * $num;
                    $content .= "{$room_type}-{$num}-{$item08['room_price']}-{$total_price},";
                }
                $list[$index]['content'] = rtrim($content,',');
                switch ($item['settlement_status']){
                    case 1: $list[$index]['settlement_status'] = '申请结算'; break;
                    case 2: $list[$index]['settlement_status'] = '未结算'; break;
                    case 3: $list[$index]['settlement_status'] = '已结算'; break;
                    default: $list[$index]['settlement_status']='申请结算';
                }
            }
        }
        //定义table键
        if (!empty($list)){
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk=>$tv){
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++){
                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis',time())."酒店安排-数据汇总数据.xls";
        $fileName = iconv('utf-8','gb2312',$fileName);
        ob_end_clean();
        if ($request->isGet()){
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename='.$fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        }else{
            // 保存文件到服务器上
            $path = ROOT_PATH."public/excel";
            // 判断文件是否存在
            if (!file_exists($path)){
                mkdir($path,0777,true);
            }
            $fileName = iconv('gb2312','utf-8',$fileName);
            $file = $path."/{$fileName}";
            $writer->save($file);
            $url =$request->domain()."/excel/{$fileName}";
            return ajax_return_adv($url,'','','','','',5);
        }
    }

    /**
     * 移到回收站
     */
    public function delete()
    {
        $data = input();
        $del = Db::name('hotel_time_price')->where('id',$data['id'])->update(['isdelete'=>1]);
        if ($del){
            return ajax_return_adv('删除成功');
        }else{
            return ajax_return_adv_error('删除失败');
        }
    }

    /**
     *  获取房型-房价-使用量-总价格
     */
    public static function getPriceList($data)
    {
        $map = [];
        // 从获取结算价格信息
        $info = Db::name('hotel_time_price')->where('id',$data['id'])->find();
        if (!$info){
            $map = [
                'room_name' => '不存在房价价格列表信息',
                'price' => 0,
                'num' => 0,
                'totalPrice' => 0,
            ];
            return $map;
        }
        // 获取该酒店的所有房型
        $hotelInfo = Db::name('room_hotel_number')->where('hotel_id',$info['hotel_id'])->select();
        if (!$hotelInfo){
            $map = [
                'room_name' => '不存在房价价格列表信息',
                'price' => 0,
                'num' => 0,
                'totalPrice' => 0,
            ];
            return $map;
        }
        // 查询该时段该酒店所有房型相对应的信息
        $roomRate = Db::name('hotel_room_price')->where('hotel_time_price_id',$data['id'])->select();
        // 根据结算价格的入住日期、结束日期，从房间记录查询酒店那段时间的所有记录
        $tian = round((strtotime($info['end_time'])-strtotime($info['start_time']))/3600/24);;
        // 把入住日期与退房日期的相差天数
        $date = [$info['start_time']];
        for ($i=1; $i<= $tian; $i++){
            array_push($date,date("Y-m-d",strtotime("+{$i} day",strtotime("{$info['start_time']}"))));//添加的
        }
        $hotelRecord = Db::name('room_consumption')->where('date_of_stay','in',$date)
            ->where('hotel_id',$info['hotel_id'])->select();
        // 组装数据
        $collectStr = []; // 组装房型、房价、数量以及总价的显示方式
        foreach ($hotelInfo as $index => $item) {
            $num = 0;
            if ($hotelRecord){
                foreach ($hotelRecord as $index01 => $item01) {
                    if ($item['hotel_id'] == $item01['hotel_id'] && $item['room_type_id'] == $item01['hotel_room_type_id'] && !empty($item01['num'])){
                        $num += $item01['num'];
                    }
                }
                $map[$index]['num'] = $num;
            }else{
                $map[$index]['num'] = $num;
            }
            $map[$index]['room_name'] = Db::name('hotel_room_type')->where('id',$item['room_type_id'])->value('room_name');
            if ($roomRate){
                foreach ($roomRate as $index02 => $item02) {
                    if ($item['hotel_id'] == $item02['hotel_id'] && $item['room_type_id'] == $item02['room_type_id']){
                        $map[$index]['price'] = $item02['room_price'];
                    }
                }
                $map[$index]['price'] = empty($map[$index]['price']) ? 0 : $map[$index]['price'];
            }else{
                $map[$index]['price'] = 0;
            }
            $map[$index]['totalPrice'] = $map[$index]['price'] * $map[$index]['num']; // 总价
//            $collectStr[] = "{$hotelInfo[$index]['room_name']} -- {$hotelInfo[$index]['price']} -- {$hotelInfo[$index]['num']} -- {$totalPrice}";
        }
        return $map;
    }

    /**
     * 还原数据
     */
    public function recycle()
    {
        $data = input();
        if (!$data['id']){
            return ajax_return_adv_error('缺少必要的参数');
        }
        $recycle = Db::name('hotel_time_price')->where('id',$data['id'])->update(['isdelete'=>0]);
        if ($recycle){
            return ajax_return_adv('还原成功');
        }else{
            return ajax_return_adv_error('还原失败');
        }
    }

    /**
     * 彻底删除
     */
    public function deleteforever()
    {
        $data = input();
        if (!$data['id']){
            return ajax_return_adv_error('缺少必要的参数');
        }
        $del = Db::name('hotel_time_price')->where('id','in',$data['id'])->delete();
        if ($del){
            return ajax_return_adv('删除成功！');
        }else{
            return ajax_return_adv_error('删除失败！');
        }
    }
    
    /**
     * 清空回收站
     */
    public function clear()
    {
        $del = Db::name('hotel_time_price')->where('isdelete',1)->delete();
        if ($del){
            return ajax_return_adv('清空回收站成功！');
        }else{
            return ajax_return_adv_error('清空回收站失败！');
        }
    }
    
    /**
     * 申请结算
     */
    public function applySettlement(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            //  验证数据
            if (!$postData['id']){
                return ajax_return_adv_error('缺少必要的参数');
            }
            $settlementData = Db::name('hotel_time_price')->where('id',$postData['id'])->find();
            if (!$settlementData){
                return ajax_return_adv_error('不存在该信息');
            }elseif ($settlementData['settlement_status'] != 1){
                return ajax_return_adv_error('结算状态不正确');
            }
            $up = Db::name('hotel_time_price')->where('id',$postData['id'])->update(['settlement_status'=>2]);
            if ($up){
                return ajax_return_adv('操作成功');
            }else{
                return ajax_return_adv_error('操作失败');
            }
       }else{
            return ajax_return_adv_error('非法请求');
        }
    }

    /**
     * 结算
     */
    public function settlement(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            // 验证数据
            if (!$postData['id']){
                return ajax_return_adv_error('缺少必要的参数');
            }
            // 查询当前的信息
            $settlementData = Db::name('hotel_time_price')->where('id',$postData['id'])->find();
            if (!$settlementData){
                return ajax_return_adv_error('不存在该信息');
            }elseif ($settlementData['settlement_status'] != 2){
                return ajax_return_adv_error('结算状态不正确');
            }
            // 更新为已结算
            $up = Db::name('hotel_time_price')->where('id',$postData['id'])->update(['settlement_status'=>3]);
            if ($up){
                return ajax_return_adv('操作成功');
            }else{
                return ajax_return_adv_error('操作失败');
            }
        }else{
            return ajax_return_adv_error('非法请求');
        }
    }

    /**
     * 未结算
     */
    public function noSettlement(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            // 验证数据
            if (!$postData['id']){
                return ajax_return_adv_error('缺少必要的参数');
            }
            // 查询当前的信息
            $settlementData = Db::name('hotel_time_price')->where('id',$postData['id'])->find();
            if (!$settlementData){
                return ajax_return_adv_error('不存在该信息');
            }elseif ($settlementData['settlement_status'] != 3){
                return ajax_return_adv_error('结算状态不正确');
            }
            // 更新为已结算
            $up = Db::name('hotel_time_price')->where('id',$postData['id'])->update(['settlement_status'=>2]);
            if ($up){
                return ajax_return_adv('操作成功');
            }else{
                return ajax_return_adv_error('操作失败');
            }
        }else{
            return ajax_return_adv_error('非法请求');
        }
    }
}
